package com.jp.knowledge.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.activity.TopicActivity;
import com.jp.knowledge.activity.TopicDetailActivity;
import com.jp.knowledge.adapter.HeadItemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.TopicAdpter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.OpenTopicDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.TopicLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.TopicInfo;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.KeyBordLayoutListener;
import com.jp.knowledge.view.TalkBottomTopicView;
import com.jp.knowledge.view.TalkBottomView;

import java.util.ArrayList;
import java.util.List;

import static com.jp.knowledge.broad.LocalBroadCast.ADD_TOPIC_BROAD;

/**
 * Created by jiayen on 16/10/12.
 * <p>
 * 话题 (资讯公司话题)
 */

public class TopicFragment extends BaseFragment implements ResultSubscriber.OnResultListener, View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, TalkBottomTopicView.ActionCallback {

    private String TAG = TopicFragment.class.getSimpleName();
    public static final int OPEN_TOPIC = 0x0000001111;//开启话题
    private static final int TOPIC_LIST = 0x0000002;//话题列表
    private static final int TOPIC_DEL = 0x0000003;//删除话题
    private Context mContext;
    private RecyclerView recyclerView;
    private RecyclerView tagList;
    private TextView name;
    private LinearLayout headLayout;
    private ImageView photo;
    private TopicAdpter adpter;
    private View contentView;
    private String topicId;
    private String infoId;
    private OpenTopicDialog openDialog;
    private HeadItemAdapter tagAdapters;
    private TalkBottomTopicView talkBottom;
    private List<TopicListInfo> list;
    private boolean fresh=true;//true刷新  false是加载
    private CanRefreshLayout mRefresh;
    private KeyBordLayoutListener keyBordLayoutListener;
    private TopicInfo topicInfos;
    private InfoData infoData;
    private View shadView;
    private TextView topicContent;
    private TextView discussNum;
    private TextView delTopic;
    private ImageView returnIcon;

    private LinearLayout praiseBtn;     // 点赞视图按钮
    private LinearLayout payRewardBtn;  // 打赏视图按钮
    private TextView praiseNumText;     // 显示点赞数量
    private TextView payRewardNumText;  // 显示打赏数量
    private int praiseNum;              // 点赞数量
    private int payRewardNum;           // 打赏数量

    private RelativeLayout noContent;

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;
    private int curPostion;//记录当前评论的位置
    private TopicLogic topicLogic;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.framgent_topic, null);
        this.mContext = getActivity();

        initView();

        return contentView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mContext == null) mContext = getActivity();

    }

    private void initView() {
        topicLogic = new TopicLogic(mContext);
        topicLogic.setTopicCallBack(new TopicLogic.TopicDataCallBack() {
            @Override
            public void done(TopicInfo topic) {
                if (topic != null && !TextUtils.isEmpty(topic.getTopicId())) {
                    topicInfos = topic;
                    if (topic != null){
                        talkBottom.setEditHint("你可继续此话题!");
                        adpter.setTopicId(topic.getTopicId());
                        getHeadlinesTopicList(0);
                    }
                    if (topic != null)
                        talkBottom.setPlNum(topic.getCount());
                    refreshHead();
                }
            }
        });
        infoData = ((TopicActivity) mContext).getInfoData();
        topicInfos = ((TopicActivity) mContext).getTopicInfo();
        this.praiseNum = topicInfos.getPraiseNum();
        this.payRewardNum = 0;

        returnIcon = (ImageView) contentView.findViewById(R.id.top_return);

        noContent = (RelativeLayout) contentView.findViewById(R.id.no_content);
        delTopic = (TextView) contentView.findViewById(R.id.del_topic);
        discussNum = (TextView) contentView.findViewById(R.id.discuss_num);
        topicContent = (TextView) contentView.findViewById(R.id.topic_content);
        mRefresh = (CanRefreshLayout) contentView.findViewById(R.id.m_refresh);

        talkBottom = (TalkBottomTopicView) contentView.findViewById(R.id.bottom_talk);
        talkBottom.setTopic(true);
        talkBottom.setInfo(infoData);
//            InfoData infoData = new InfoData();
        talkBottom.setTopic(((TopicActivity) getActivity()).getTopicInfo());
        talkBottom.setActionCallback(this);
        talkBottom.setTopicInfo(topicInfos);

        topicId = ((TopicActivity) mContext).getTopicId();
        infoId = ((TopicActivity) mContext).getInfoId();
        //顶部
        photo = (ImageView) contentView.findViewById(R.id.photo);
        headLayout = (LinearLayout) contentView.findViewById(R.id.head_layout);
        name = (TextView) contentView.findViewById(R.id.name);
        tagList = (RecyclerView) contentView.findViewById(R.id.tag_list);
        shadView = contentView.findViewById(R.id.shade_view);
        talkBottom.setShadeView(shadView);
        shadView.setOnClickListener(this);

        praiseBtn = (LinearLayout) contentView.findViewById(R.id.topic_praise_btn);
        payRewardBtn = (LinearLayout) contentView.findViewById(R.id.topic_reward_btn);
        praiseNumText = (TextView) contentView.findViewById(R.id.topic_praise_num);
        payRewardNumText = (TextView) contentView.findViewById(R.id.topic_reward_num);
        praiseBtn.setOnClickListener(this);
        payRewardBtn.setOnClickListener(this);

        praiseNumText.setText(this.praiseNum + "");
        payRewardNumText.setText(this.payRewardNum + "");
        talkBottom.setPraiseNum(this.praiseNum);
        talkBottom.setPayRewardNum(this.payRewardNum);

        recyclerView = (RecyclerView) contentView.findViewById(R.id.can_content_view);//公司话题
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adpter = new TopicAdpter(mContext, null);
        if (topicInfos != null)
            adpter.setTopicId(topicInfos.getTopicId());
        recyclerView.setAdapter(adpter);

        if (topicInfos != null) {
            if (topicInfos.getTopicId() != null) {
                setTopicInfoData(topicInfos, false);
                talkBottom.setEditHint("你可继续此话题!");
                talkBottom.setPlNum(topicInfos.getCount());
                getHeadlinesTopicList(0);
            } else {
                talkBottom.setPlNum(0);
                noContent.setVisibility(View.VISIBLE);
                if (infoData != null)
                    topicLogic.getTopicData(infoData.getType(), infoData.getId());
            }
        } else {
            talkBottom.setPlNum(0);
            noContent.setVisibility(View.VISIBLE);
            if (infoData != null)
                topicLogic.getTopicData(infoData.getType(), infoData.getId());
        }


        talkBottom.setInfoId(infoId);
//        talkBottom.hidePl();
        talkBottom.setCommentUtil(new TalkBottomView.CommentUtil() {
            @Override
            public void done(TopicListInfo info) {
                if (topicInfos != null && topicInfos.getTopicId() != null) {
//                    getHeadlinesTopicList(0);
                }
            }
        });
        mRefresh.setLoadMoreEnabled(true);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
        adpter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                curPostion = position;
                TopicListInfo info = list.get(position);
                Intent intent = new Intent(mContext, TopicDetailActivity.class);
                intent.putExtra("commentId", info.getCommentId());
                info.setInfoId(infoId);
                intent.putExtra("infoId", infoId);
                intent.putExtra("topicId", topicId);
                intent.putExtra("toUid", info.getUid());
                intent.putExtra("toCommentId", info.getCommentId());
                intent.putExtra("content", info.getContent());
                intent.putExtra("info_icon", ((TopicActivity) mContext).getInfoPic());
                intent.putExtra("info_title", ((TopicActivity) mContext).getInfoTitle());
                intent.putExtra("username", info.getNickName());
                intent.putExtra("pic", info.getPortrait());
                intent.putExtra("info", info);
                intent.putExtra("time", info.getTime());
                intent.putExtra("prise", info.getPraiseNum());
                ((TopicActivity) mContext).startActivityForResult(intent, 1);
            }
        });

        adpter.setInfoId(infoId);
        keyBordLayoutListener = new KeyBordLayoutListener();
        keyBordLayoutListener.setRootView(talkBottom);
        keyBordLayoutListener.setListener(new KeyBordLayoutListener.KeyBordListener() {
            @Override
            public void onHideKeyboard() {
                L.e("onHideKeyboard");
                talkBottom.hideEdit();
                if (shadView != null)
                    shadView.setVisibility(View.GONE);
                talkBottom.clearEdit();
            }

            @Override
            public void onShowKeyboard() {
                L.e("onShowKeyboard");
                talkBottom.showEdit();
            }
        });
        talkBottom.getViewTreeObserver().addOnGlobalLayoutListener(keyBordLayoutListener);


        refreshHead();//刷新头部数据

        //增加监听话题 回调
        talkBottom.setAddCommentHand(new TalkBottomView.AddCommentHand() {
            @Override
            public void done(TopicListInfo topicInfo) {
                if (list == null) list = new ArrayList<TopicListInfo>();
                list.add(0, topicInfo);
                adpter.update(list);
            }
        });

        returnIcon.setOnClickListener(this);

        registerBroadCast();

    }


    private void refreshHead() {
        setTopicInfoData(topicInfos,false);
        if (topicInfos != null) {
            if (topicInfos.getTopicId() != null) {
                setTopicInfoData(topicInfos, false);
                talkBottom.setEditHint("你可继续此话题!");
                talkBottom.setPlNum(topicInfos.getCount());

                noContent.setVisibility(View.GONE);
            } else {
                talkBottom.setPlNum(0);
                noContent.setVisibility(View.VISIBLE);
            }
        } else {
            talkBottom.setPlNum(0);
            noContent.setVisibility(View.VISIBLE);
        }


        if (topicInfos != null) {
            discussNum.setText(topicInfos.getDiscuss() + "家公司讨论过");
            topicContent.setText(topicInfos.getContent());

            if (topicInfos.getUserId() != null && topicInfos.getUserId().equals(HttpHelper.uuid)) {//说明是自己的
                delTopic.setVisibility(View.VISIBLE);
                delTopic.setOnClickListener(this);

            } else {
                delTopic.setVisibility(View.GONE);

            }
        }
    }

    /**
     * 使用广播刷新数据
     */
    private void registerBroadCast() {
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(LocalBroadCast.PRISE_BROAD)) {//点赞广播
//                    talkBottom.setScIcon();//改变标识
                    list.get(curPostion).setIsPraise(1);
                    list.get(curPostion).setPraiseNum(list.get(curPostion).getPraiseNum() + 1);
                    adpter.update(list);
                } else if (action.equals(LocalBroadCast.ADD_TOPIC_BROAD)) {
                    TopicInfo topic = intent.getParcelableExtra("topic");
                    topicInfos = topic;
                    if (topic != null){
                        talkBottom.setEditHint("你可继续此话题!");
                        adpter.setTopicId(topic.getTopicId());
                        getHeadlinesTopicList(0);
                    }
                    if (topic != null)
                        talkBottom.setPlNum(topic.getCount());
                    refreshHead();
                }
            }
        });
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.PRISE_BROAD);
        intentFilter.addAction(LocalBroadCast.ADD_TOPIC_BROAD);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        talkBottom.getViewTreeObserver().removeOnGlobalLayoutListener(keyBordLayoutListener);
        localBroadcastManager.unregisterReceiver(localBroadCast);
    }

    /**
     * 获取话题列表数据
     */
    private void getHeadlinesTopicList(int mode) {
        JsonObject param = new JsonObject();
        param.addProperty("topicId", topicInfos.getTopicId());
        param.addProperty("type", infoData.getType());
        long time = 0;
        if (list != null) {
            if (mode == 0) {
                fresh = true;
                time = list.get(0).getTime();
            } else {
                fresh = false;
                time = list.get(list.size() - 1).getTime();
            }
        }
        param.addProperty("time", time);
        param.addProperty("mode", mode);
        HttpHelper.getInstance(mContext).headlinesTopicList(param, TOPIC_LIST, this);

    }

    @Override
    public void onStart(int requestType) {
        loadingDialog.show();
    }

    @Override
    public void onCompleted(int requestType) {
        if (requestType == TOPIC_LIST) {
            mRefresh.refreshComplete();
            mRefresh.loadMoreComplete();
        }
        loadingDialog.cancel();
    }

    @Override
    public void onError(int requestType) {
        loadingDialog.cancel();
        if (requestType == TOPIC_LIST) {
            mRefresh.refreshComplete();
            mRefresh.loadMoreComplete();
        }
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if (requestType == OPEN_TOPIC) {//开启话题返回
            handOpenTopic(data);//处理开启话题列表
        } else if (requestType == TOPIC_LIST) {//获取话题列表返回
            handTopicList(data);//处理话题列表数据
        } else if (requestType == TOPIC_DEL) {
            if (data.getErrcode() == 0) {//删除成功则关闭话题
                Intent intent = new Intent(ADD_TOPIC_BROAD);
                intent.putExtra("topic", new TopicInfo());//发送广播通知详情页更新话题
                localBroadcastManager.sendBroadcast(intent);
                ((Activity) mContext).finish();
            } else {
                ToasUtil.toast(mContext, data.getMessage());
            }
        }
    }

    /**
     * 处理话题列表数据
     *
     * @param data
     */
    private void handTopicList(IModel data) {
        Object obj = data.getData();
        if (data.getErrcode() == 0) {//获取数据成功
            if (obj == null || obj.equals(new ArrayList()) || obj.equals("[]")) {
                ToasUtil.toast(mContext, "暂无更多评论!");
                return;
            }

            if (list == null) list = new ArrayList<>();
            List<TopicListInfo> temp = data.getList(TopicListInfo.class);
            if (fresh) {//刷新
                list = temp;
            } else {//加载更多
                list.addAll(temp);
            }
            adpter.update(list);
        } else if (data.getErrcode() == 110113) {
            startActivity(new Intent(mContext, LoginActivity.class));
        } else {
            ToasUtil.toast(mContext, "获取列表数据失败");
        }
    }

    /**
     * 处理开启话题列表
     *
     * @param data
     */
    private void handOpenTopic(IModel data) {
        L.d(TAG, "====" + data.toString());
        if (data.getErrcode() == 0) {//开启成功
            Object obj = data.getData();
            if (obj != null) {
                LinkedTreeMap map = (LinkedTreeMap) obj;
                TopicInfo topic = JsonUtil.getInstance().mapToObject(map, TopicInfo.class);
                setTopicInfoData(topic, true);
                //设置完成后 获取话题列表数据
                getHeadlinesTopicList(0);
            }

        } else if (data.getErrcode() == 110113) {//尚未登录 则跳到登录页面
            startActivity(new Intent(mContext, LoginActivity.class));
        } else {
            ToasUtil.toast(mContext, "开启话题失败");
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shade_view:
                talkBottom.hideSoftAndEdit();
                shadView.setVisibility(View.GONE);
                break;
            case R.id.del_topic://删除话题
                deleteTopic();
                break;
            case R.id.top_return:
                ((Activity) mContext).finish();
                break;
            case R.id.topic_praise_btn:     // 点赞视图按钮
                if(topicInfos.getIsPraise() == 0)
                    talkBottom.doPraise();
                else
                    ToasUtil.toast(mContext, "请勿重复点赞");
                break;
            case R.id.topic_reward_btn:     // 打赏视图按钮
                talkBottom.doPayreward();
                break;
            default:
                break;
        }
    }

    /**
     * 删除话题
     */
    private CommDialog commDialog;

    private void deleteTopic() {
        if (commDialog == null) {
            commDialog = new CommDialog(mContext);
            commDialog.setContent("你确定删除吗?");
            commDialog.setRight("删除");
            commDialog.setRightListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JsonObject param = new JsonObject();
                    param.addProperty("topicId", topicInfos.getTopicId());
                    HttpHelper.getInstance(mContext).topicDelete(param, TOPIC_DEL, TopicFragment.this);
                }
            });
        }
        commDialog.show();
    }

    /**
     * 设置topichead数据
     *
     * @param topic
     */
    private void setTopicInfoData(TopicInfo topic, boolean save) {
//        topic.setInfoId(infoId);
//        topic.setTag(topic.getTags());
        //保存进数据库缓存
        if (save)
            DBHelper.getInstance().save(topic);

        topicId = topic.getTopicId();
        talkBottom.setInfoId(infoId);
        talkBottom.setTopicId(topicId);
        headLayout.setVisibility(View.VISIBLE);

//        Glide.with(context).load(topic.getPortrait()).bitmapTransform(new CropCircleTransformation(context)).override(30, 30).into(photo);//new BlurTransformation(getContext(), 25),
        ImageLoadUtil.loadCircle(mContext, topic.getPortrait(), photo, 30, 30);
        name.setText(topic.getUserName());

        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 5);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        tagList.setLayoutManager(layoutManager);


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRefresh() {
        fresh = true;
        getHeadlinesTopicList(0);
    }

    @Override
    public void onLoadMore() {
        fresh = false;
        getHeadlinesTopicList(1);
    }

    /* 点赞回调 */
    @Override
    public void praiseCallback(boolean isSuccess) {
        if(!isSuccess) {
            ToasUtil.toast(mContext, "抱歉，操作失败，请稍后重试");
            return;
        }
        topicInfos.setIsPraise(1);
        topicInfos.setPraiseNum(++this.praiseNum);
        praiseNumText.setText(praiseNum + "");
        talkBottom.setPraiseNum(praiseNum);
    }
    /* 打赏回调 */
    @Override
    public void payCewardBallback(boolean isSuccess) {
//        if(!isSuccess)
//            return;
//        payRewardNumText.setText(++payRewardNum + "");
//        talkBottom.setPayRewardNum(payRewardNum);
    }
}
